package com.sfeir.server.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.googlecode.objectify.Query;
import com.sfeir.client.util.Constants;
import com.sfeir.client.util.Utils;
import com.sfeir.shared.Score;

/**
 * Score Dao Implementation
 * 
 * @author Oussama Zoghlami
 * @date 30/12/2011
 * 
 */
public class ScoreDao extends ObjectifyDao<Score> {

	public ScoreDao() {
		super(Score.class);
	}

	/**
	 * 
	 * @param userEmail
	 * @param levelOrder
	 * @return
	 */
	public Score getUserScore(String userEmail, int levelOrder) {
		Query<Score> q = ofy().query(Score.class);
		q.filter("userEmail", userEmail);
		q.filter("levelOrder", levelOrder);
		return q.get();
	}

	/**
	 * Method allowing to save the score associated to a given user and level.
	 * 
	 * @param userEmail
	 * @param levelOrder
	 * @param scoreNumber
	 */
	public int saveUserScore(String userEmail, String userNickName, int levelOrder, int scoreNumber) {
		Query<Score> q = ofy().query(Score.class);
		q.filter("userEmail", userEmail);
		q.filter("levelOrder", levelOrder);
		Score score = q.get();
		if (null != score) {
			if (score.getScore() > scoreNumber) {
				score.setScore(scoreNumber);
				ofy().put(score);
			}
		} else {
			ofy().put(new Score(scoreNumber, userEmail, userNickName, levelOrder));
		}
		return Utils.getScoreStars(scoreNumber, levelOrder);
	}

	/**
	 * Method allowing to return the user score just before a given score and
	 * associated to a give, level
	 * 
	 * @param level
	 * @param score
	 * @return
	 */
	public Map<String, Object> getFirstLowerToScore(int level, int score) {
		Query<Score> q = ofy().query(Score.class);
		q.filter("levelOrder", level);
		if (score != 0) {
			q.filter("score <", score);
		}
		q.order("score");
		List<Score> scores = q.list();
		if ((null != scores) && (scores.size()) > 0) {
			Map<String, Object> map = new HashMap<String, Object>();
			Score nextToBeatScore = scores.get(scores.size() - 1);
			map.put(Constants.MAP_NEXT_USER_TOBEAT, nextToBeatScore.getUserNickName());
			map.put(Constants.MAP_NEXT_USER_TOBEAT_SCORE, nextToBeatScore.getScore());
			return map;
		}
		return null;
	}
}
